package com.dianpingmedia.wifitz.dao;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import com.dianpingmedia.wifitz.entiy.MacCollect;
import com.dianpingmedia.wifitz.entiy.MacFile;
import com.dianpingmedia.wifitz.entiy.ProbeDataCollect;
import com.dianpingmedia.wifitz.entiy.WifiTzData;
import com.dianpingmedia.wifitz.utlis.ByteUtil;
import com.dianpingmedia.wifitz.utlis.FileUtil;
import com.dianpingmedia.wifitz.utlis.MacArrayList;
import com.dianpingmedia.wifitz.utlis.RssiMeterUtil;
import com.dianpingmedia.wifitz.utlis.SPUtils;
import com.dianpingmedia.wifitz.utlis.ZipUtil;

import org.apache.tools.ant.taskdefs.Zip;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;

/**
 * @author zsc
 * @create 2018/4/8 0008
 * @Describe
 */
public class TzDataSaveManager {
    private static final SimpleDateFormat mFormat = new SimpleDateFormat("HHmmss", Locale.getDefault());
    private static final SimpleDateFormat mFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    private DaoManager mManager = DaoManager.getInstance();
    private Handler mSaveHandler;
    private Handler logHandler;
    private final static String TAG = TzDataSaveManager.class.getSimpleName();
    private ProbeDataCollect mProbeDataCollec = new ProbeDataCollect();



    public TzDataSaveManager(Context context) {
        HandlerThread saveHandlerThread = new HandlerThread("save");
        saveHandlerThread.start();
        mSaveHandler = new Handler(saveHandlerThread.getLooper());
        mManager.init(context);
    }

    public void postInsert(final String data) {
            mSaveHandler.post(new Runnable() {
                @Override
                public void run() {
                    String[] macList = data.split("\n");
                    for (String macStr : macList) {
                        ProbeDataCollect.ProbeData probeData = null;
                        try {
                            probeData = new ProbeDataCollect.ProbeData();
                            String[] split = macStr.split("\\|");
                            probeData.setM_strTime(Integer.parseInt(mFormat.format(new Date())));
                            probeData.setM_strWiFiProbeMac(split[0]);
                            probeData.setM_strSrcMac(split[1]);
                            probeData.setM_strObjMac(split[2]);
                            String sortBigStr = split[3];
                            String bySortSmallStr = split[4];
                            int sortBig = Integer.parseInt(sortBigStr, 16);
                            int sortSmall = Integer.parseInt(bySortSmallStr, 16);
                            probeData.setM_bySortBig(sortBig);
                            probeData.setM_bySortSmall(sortSmall);
                            probeData.setM_iChannel(Integer.parseInt(split[5]));
                            String rssi = split[6];
                            probeData.setM_iCellPower(Integer.parseInt(rssi));
                            if (!RssiMeterUtil.within(rssi, SPUtils.getRang())) {
                                String msg = "信号强度不在范围内对丢弃处理:" + probeData;
                                Log.e(TAG, msg);
                                continue;
                            }
                            insert(probeData);
                        } catch (Exception e) {
                            e.printStackTrace();
                            String msg = "数据解析失败:" + macStr;
                            Log.e(TAG, msg);
                            sendLog(msg);
                        }
                    }
                    doPack();
                }
            });
    }

    private void doPack() {
        sendSizeLog(mProbeDataCollec.getSize() + "");
        if (mProbeDataCollec.isOutOfSize(SPUtils.getCount())) {
            sendLog("当前超过" + SPUtils.getCount() + "条，打成一个包\n");
            try {
                byte[] rawBytes = mProbeDataCollec.toString().getBytes("ASCII");
                byte[] zip = ZipUtil.zip(rawBytes);
                sendLog("原数据大小:" + rawBytes.length + "\n");
                sendLog("压缩后大小zip:" + zip.length + "\n");
                MacFile entity = new MacFile();
                entity.setTime(System.currentTimeMillis());
                //
                //                try {
                //                    byte[] bytes = ZipUtil.unZip(zip);
                //                    String raw = new String(bytes, "ASCII");
                //                    Log.d("TzDataSaveManager","解压还原:"+raw);
                //                } catch (UnsupportedEncodingException e) {
                //                    e.printStackTrace();
                //                }
                entity.setJsonDestMac(mProbeDataCollec.destMacsToJson());

                entity.setFile(zip);
                //目标wifi地址
                entity.setDestMac(mProbeDataCollec.getProbeDataInit().getM_strDestMac());
                //wifi探针的地址
                entity.setWiFiProbeMac(mProbeDataCollec.getProbeDataInit().getM_strWiFiProbeMac());
                sendLog("打包日期:" + mFormat2.format(entity.getTime()) + "\n");
                sendLog("插入数据:" + entity.toString() + "\n");

                long insert = mManager.getDaoSession().getMacFileDao().insert(entity);
                //重置
                mProbeDataCollec.clear();
                mProbeDataCollec.updateTime();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存一条记录or插入一条记录
     *
     * @param probeData
     */
    private void insert(ProbeDataCollect.ProbeData probeData) {
        String date = mFormat.format(new Date());
        WifiTzData entity = new WifiTzData();
        entity.setMac(probeData.getM_strSrcMac());
        entity.setMajor(probeData.getM_bySortBig());
        entity.setMinor(probeData.getM_bySortSmall());
        entity.setPower(probeData.getM_iCellPower());
        entity.setChannel(probeData.getM_iChannel());
        entity.setTime(date);
        entity.setMeter(RssiMeterUtil.rssiToMeter(probeData.getM_iCellPower()) + "");
        mManager.getDaoSession().getWifiTzDataDao().insert(entity);
        mProbeDataCollec.add(probeData);
        mProbeDataCollec.addStrObjMac(probeData.getM_strObjMac());
        mProbeDataCollec.setM_strDate(date);
        mProbeDataCollec.setM_strWiFiProbeMac(probeData.getM_strWiFiProbeMac());
    }

    public void setHandler(Handler handler) {
        logHandler = handler;
    }


    private void sendLog(String log) {
        if (logHandler != null) {
            Message obtain = Message.obtain();
            obtain.what = 0;
            obtain.obj = log;
            logHandler.sendMessage(obtain);
        }
    }

    private void sendSizeLog(String log) {
        if (logHandler != null) {
            Message obtain = Message.obtain();
            obtain.what = 2;
            obtain.obj = log;
            logHandler.sendMessage(obtain);
        }
    }


    public void release() {
        try {
            mManager.closeConnection();
            mManager.closeHelper();
            mManager.closeDaoSession();
            mSaveHandler.removeCallbacksAndMessages(null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                mSaveHandler.getLooper().quitSafely();
            } else {
                mSaveHandler.getLooper().quit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
